package com.prodog.gamemodule.gameworld.map.service.impl;

import com.prodog.command.annonations.Service;
import com.prodog.command.entity.CommandResult;
import com.prodog.command.entity.RoleGameCommand;
import com.prodog.gamemodule.gameworld.map.builder.MapInfoBuilder;
import com.prodog.gamemodule.gameworld.map.checker.MoveMapCheckRes;
import com.prodog.gamemodule.gameworld.map.checker.MoveMapCheckerStack;
import com.prodog.gamemodule.gameworld.map.entity.GameMap;
import com.prodog.gamemodule.gameworld.map.service.GameMapService;
import com.prodog.gamemodule.gameworld.map.wrapper.GameMapWrapper;
import com.prodog.usermodule.role.wrapper.RoleInfoWrapper;
import lombok.RequiredArgsConstructor;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class GameMapServiceImpl implements GameMapService {
    private final GameMapWrapper mapWrapper;
    private final RoleInfoWrapper roleInfoWrapper;

    private final Map<String, String> directMap = new HashMap<String, String>() {{
        put("上", "up");
        put("下", "down");
        put("左", "left");
        put("右", "right");
    }};

    @Override
    public CommandResult move(RoleGameCommand command, String direction) throws Exception {
        String direct = directMap.get(direction);
        GameMap curMap = mapWrapper.getByStr(command.getRoleInfo().getMapId());
        Field field = GameMap.class.getDeclaredField(direct);
        field.setAccessible(true);
        String val = (String) field.get(curMap);
        return move(command, curMap, mapWrapper.getByStr(val));
    }

    @Override
    public CommandResult move(RoleGameCommand command, GameMap curMap, GameMap moveMap) {
        //检查器栈检查是否可通行
        MoveMapCheckRes checkRes = new MoveMapCheckerStack(command, curMap, moveMap).check();
        if (!checkRes.isPass()) {
            return CommandResult.failure(command.getRoleInfo().getPrefix() + checkRes.getMsg());
        }
        //通过位置面板生成器生成位置信息 返回
        command.getRoleInfo().setMapId(moveMap.getId());
        roleInfoWrapper.save(command.getRoleInfo());
        MapInfoBuilder builder = new MapInfoBuilder(command, curMap, moveMap);
        return CommandResult.success(command.getRoleInfo().getPrefix() + builder.build());
    }

    @Override
    public CommandResult currentMap(RoleGameCommand command) {
        GameMap curMap = mapWrapper.getByStr(command.getRoleInfo().getMapId());
        MapInfoBuilder builder = new MapInfoBuilder(command, curMap, curMap);
        return CommandResult.success(command.getRoleInfo().getPrefix() + builder.build());
    }
}
